﻿using AutoMapper;
using B.T.BasicData.Domain.RBAC;
using B.T.BasicData.ErrorCode;
using B.T.BasicData.Infraeturcture;
using B.T.BasicData.Write_Api.DTO;
using B.T.BasicData.Write_Api.RBAC.IServices;
using MD5Hash;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography;
using System.Text;
using Yitter.IdGenerator;

namespace B.T.BasicData.Write_Api.RBAC.Services
{
    public class UserServices : IUserServices
    {
        private readonly ILogger<UserServices> logger;
        private readonly IBaseRepository<Userinfo> userinfo;
        private readonly IBaseRepository<User_Role> userRoleRepo;
        private readonly MyDbContext dbContext;
        private readonly IMapper _mapper;
        private readonly IBaseRepository<RolesInfo> rolesinfo;

        public UserServices(ILogger<UserServices> logger, IBaseRepository<Userinfo> userinfo, IBaseRepository<User_Role> userRoleRepo, MyDbContext dbContext, IMapper mapper,IBaseRepository<RolesInfo> rolesinfo)
        {
            this.logger = logger;
            this.userinfo = userinfo;
            this.userRoleRepo = userRoleRepo;
            this.dbContext = dbContext;
            _mapper = mapper;
            this.rolesinfo = rolesinfo;
        }
        /// <summary>
        /// 对明文密码进行MD5加密
        /// </summary>
        /// <param name="password">明文密码</param>
        /// <returns>加密后的字符串</returns>
        private string Md5Encrypt(string password)
        {
            using (var md5 = MD5.Create())
            {
                var bytes = Encoding.UTF8.GetBytes(password);
                var hash = md5.ComputeHash(bytes);
                return BitConverter.ToString(hash).Replace("-", "").ToLower();
            }
        }
        /// <summary>
        /// 创建用户信息，并同时写入用户角色关系表，使用事务保证数据一致性。
        /// </summary>
        /// <param name="dto">包含用户基本信息和角色Id列表的DTO</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> AddUserinfo(AddUserinfoDto dto)
        {
            var res = new ApiResult();
            var strategy = dbContext.Database.CreateExecutionStrategy();
            await strategy.ExecuteAsync(async () =>
            {
                using (var tran = await dbContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        // 构建用户实体
                        var user = new Userinfo
                        {
                            UserId = Yitter.IdGenerator.YitIdHelper.NextId(), // 生成唯一用户ID
                            UserName = dto.UserName,
                            Password = dto.Password.GetMD5(), // 密码MD5加密
                            Serialnumber = dto.Serialnumber,
                            CreateTime =DateTime.Now,
                            status = true,
                            IsDeleted = false
                        };
                        // 写入用户信息
                        var addUserResult = await userinfo.AddAnyx(user);
                        if (addUserResult <= 0)
                        {
                            res.msg = "用户添加失败";
                            return;
                        }
                        // 批量写入用户-角色关系
                        foreach (var rid in dto.RolesId)
                        {
                            var userRole = new User_Role
                            {
                                UserId = user.UserId,
                                RolesId = rid,
                                IsDele = false
                            };
                            await userRoleRepo.AddAnyx(userRole);
                        }
                        // 提交事务
                        await tran.CommitAsync();
                        res.success("用户及角色关系添加成功");
                    }
                    catch (Exception ex)
                    {
                        // 回滚事务，保证数据一致性
                        await tran.RollbackAsync();
                        logger.LogError("异常：" + ex.Message);
                    }
                }
            });
            return res;
        }


        /// <summary>
        /// 删除用户信息（软删除）
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> DeleteUser(long userId)
        {
            var res = new ApiResult();
            var user = userinfo.Getlist().FirstOrDefault(x => x.UserId == userId && !x.IsDeleted);
            if (user == null)
            {
                res.msg = "未找到该用户";
                return res;
            }
            user.IsDeleted = true;
            var result = await userinfo.Update(user);
            if (result > 0)
            {
                res.success("用户删除成功");
            }
            else
            {
                res.msg = "用户删除失败";
            }
            return res;
        }

        /// <summary>
        /// 编辑用户信息及其角色
        /// </summary>
        /// <param name="dto">用户信息编辑DTO</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> UpdateUserinfo(UpdateUserinfoDto dto)
        {
            var res = new ApiResult();
            var strategy = dbContext.Database.CreateExecutionStrategy();
            await strategy.ExecuteAsync(async () =>
            {
                using (var tran = await dbContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        // 查找用户
                        var user = userinfo.Getlist().FirstOrDefault(x => x.UserId == dto.UserId && !x.IsDeleted);
                        if (user == null)
                        {
                            res.msg = "未找到该用户";
                            return;
                        }
                        // 更新用户基本信息
                        user.UserName = dto.UserName;
                        user.Password = dto.Password;
                        user.status = dto.status;
                        user.Serialnumber = dto.Serialnumber;
                        user.CreateTime = dto.CreateTime;
                        user.IsDeleted = dto.IsDeleted;
                        var updateResult = await userinfo.Update(user);
                        if (updateResult <= 0)
                        {
                            res.msg = "用户信息更新失败";
                            return;
                        }
                        // 先删除原有的用户角色关系
                        var oldRoles = userRoleRepo.Getlist().Where(x => x.UserId == user.UserId && !x.IsDele).ToList();
                        foreach (var old in oldRoles)
                        {
                            old.IsDele = true;
                            await userRoleRepo.Update(old);
                        }
                        // 添加新的用户角色关系
                        foreach (var rid in dto.RolesId)
                        {
                            var userRole = new User_Role
                            {
                                UserId = user.UserId,
                                RolesId = rid,
                                IsDele = false
                            };
                            await userRoleRepo.AddAnyx(userRole);
                        }
                        //提交事务
                        await tran.CommitAsync();
                        res.success("用户信息及角色更新成功");
                    }
                    catch (Exception ex)
                    {
                        //出现错误自动报错
                        await tran.RollbackAsync();
                        logger.LogError("异常：" + ex.Message);
                        res.msg = "用户信息更新异常";
                    }
                }
            });
            return res;
        }
    }
}
